//
//  CXHTradPlusInterstitialAdapter.m
//  CXHAdSDK-TradPlus
//
//  Created by 陈坤 on 2023/9/20.
//

#import "CXHTradPlusInterstitialAdapter.h"
#import <TradPlusAds/TradPlusAdWaterfallItem.h>
#import <CXHAdSDK-Core/CXHAdSDK.h>
#import <CXHAdSDK-Core/CXHAdSDKInterstitialAd.h>
#import <CXHAdSDK-Kit/CXHUtilsKit.h>

@interface CXHTradPlusInterstitialAdapter ()<CXHAdSDKInterstitialAdDelegate>

@property(nonatomic, strong) CXHAdSDKInterstitialAd *interstitialAd;

@property (nonatomic, assign) BOOL isInit;

@property (nonatomic, assign) BOOL isC2SBidding;

@end

@implementation CXHTradPlusInterstitialAdapter

//根据event实现相关流程
- (BOOL)extraActWithEvent:(NSString *)event info:(NSDictionary *)config
{
    if([event isEqualToString:@"C2SBidding"]){
        //从三方SDK获取价格
        [self getECPMC2SBidding];
    } else if([event isEqualToString:@"LoadAdC2SBidding"]) {
        //竞价成功后的加载流程
//        [self.interstitialAd sendWinNotice:self.interstitialAd.getBidPrice];
        [self loadAdC2SBidding];
    } else if ([event isEqualToString:@"C2SLoss"]) {
        NSString *topPirce = config[@"topPirce_cny"];
        [self.interstitialAd sendLossNotice:[topPirce integerValue]];
    } else {
        return NO;
    }
    return YES;
}

- (void)loadAdC2SBidding {
    if ([self isReady]) {
        [self.interstitialAd sendWinNotice:self.interstitialAd.getBidPrice];
        [self AdLoadFinsh];
    }else{
        NSError *loadError = [NSError errorWithDomain:@"Load interstitial failed" code:-4 userInfo:@{NSLocalizedDescriptionKey : @"C2S interstitial not ready"}];
        [self AdLoadFailWithError:loadError];
    }
}

- (void)getECPMC2SBidding {
    [self startC2SBidding];
}

//通过三方API获取ECPM
- (void)startC2SBidding {
    self.isC2SBidding = YES;
    
    NSString *posid = self.waterfallItem.config[@"posid"];
    
    if (kCXHStringIsEmpty(posid)) {
        NSDictionary *dic = @{@"error": @"get bid price failed"};
        [self ADLoadExtraCallbackWithEvent:@"C2SBiddingFail" info:dic];
        return;
    }
    
    self.interstitialAd.posId = posid;
    
    [self loadAdWithWaterfallItem:self.waterfallItem];
}

- (CXHAdSDKInterstitialAd *)interstitialAd{
    if (_interstitialAd == nil) {
        _interstitialAd = [[CXHAdSDKInterstitialAd alloc] init];
        _interstitialAd.delegate = self;
    }
    return _interstitialAd;
}

//初始化自定义平台，设置平台参数（海外平台的隐私设置）加载广告
- (void)loadAdWithWaterfallItem:(TradPlusAdWaterfallItem *)item
{
    [self initSDK:item.config];
    //通过 item.config 获取后台配置信息
    NSString *posid = item.config[@"posid"];
    
    if (kCXHStringIsEmpty(posid)) {
        [self  AdConfigError];
        return;
    }
    
    self.interstitialAd.posId = posid;
    NSDictionary *localParams = [item.extraInfoDictionary CXH_objectOrNilForKey:@"localParams"];
    if (localParams) {
        id isClose = [localParams CXH_objectOrNilForKey:@"showclose"];
        if (isClose != nil && [isClose isEqualToString:@"true"]) {
            _interstitialAd.hiddenCloseView = YES;
        }
        
        id showTime = [localParams CXH_objectOrNilForKey:@"showtime"];
        if (showTime != nil) {
            _interstitialAd.showTime = [showTime intValue];
        }
        
        id touchClose = [localParams CXH_objectOrNilForKey:@"touchclose"];
        if (touchClose != nil && [touchClose isEqualToString:@"true"]) {
            _interstitialAd.touchClose = YES;
        }
    }
    
    [_interstitialAd loadAdData];
}

- (void)initSDK:(NSDictionary *)config {
    if (self.isInit) {
        return;
    }
    self.isInit = YES;
    NSString *domain = [config CXH_objectOrNilForKey:@"domain"];
    if (kCXHStringIsEmpty(domain)) {
        domain = @"";
    }
    
    NSString *appid = [config CXH_objectOrNilForKey:@"appid"];
    if (!kCXHStringIsEmpty(appid)) {
        [CXHAdSDK initWithAppId:appid requestDomain:domain completionBlock:^(NSError * _Nullable error) {
            if (error) {
                [self AdConfigError];
            }
        }];
    }
}

//展示广告
- (void)showAdFromRootViewController:(UIViewController *)rootViewController{
    self.interstitialAd.controller = rootViewController;
    [self.interstitialAd show];
}

//此方法用于返回是否过期状态
- (BOOL)isReady
{
    return [self.interstitialAd isAdValid];
}

/**
 CXHAdSDKIntertitialAd请求成功回调
 
 @param interstitialAd 插屏广告实例对象
*/
- (void)CXH_interstitialAdSuccedToLoad:(CXHAdSDKInterstitialAd *)interstitialAd{
    if (self.isC2SBidding) {
        NSInteger price = self.interstitialAd.getBidPrice;
        if (price <= 0) {
            NSDictionary *dic = @{@"error": @"get bid price failed"};
            [self ADLoadExtraCallbackWithEvent:@"C2SBiddingFail" info:dic];
            return;
        }
        //通过接口向TradPlusSDK回传ecpm和三方版本号
        float f = price/100.00;
        NSString *ecpmStr = [NSString stringWithFormat:@"%.2f", f];
        NSDictionary *dic = @{@"ecpm":ecpmStr,@"version":[CXHAdSDK getSDKVersion]};
        [self ADLoadExtraCallbackWithEvent:@"C2SBiddingFinish" info:dic];
    } else {
        [self AdLoadFinsh];
    }
}

/**
 CXHAdSDKIntertitialAd请求失败回调

 @param interstitialAd 插屏广告实例对象
 @param error 失败原因
*/
- (void)CXH_interstitialAdFailedToLoad:(CXHAdSDKInterstitialAd *)interstitialAd error:(NSError *)error{
    [self AdLoadFailWithError:error];
}

/**
 CXHAdSDKIntertitialAd展示在屏幕内回调

 @param interstitialAd 插屏广告实例对象
*/
- (void)CXH_interstitialAdDidPresent:(CXHAdSDKInterstitialAd *)interstitialAd{
    
}

/**
 CXHAdSDKIntertitialAd展示在屏幕内失败回调

 @param interstitialAd 插屏广告实例对象
*/
- (void)CXH_interstitialAdFailedToPresent:(CXHAdSDKInterstitialAd *)interstitialAd error:(NSError *)error{
    [self AdShowFailWithError:error];
}

/**
 CXHAdSDKIntertitialAd点击回调

 @param interstitialAd 插屏广告实例对象
 @param loadingPageURL 广告落地页地址，当渠道为bwt，并且customLoadingPage为YES时有值
*/
- (void)CXH_interstitialAdDidClick:(CXHAdSDKInterstitialAd *)interstitialAd loadingPageURL:(NSString *)loadingPageURL{
    [self AdClick];
}

/**
 CXHAdSDKIntertitialAd关闭回调

 @param interstitialAd 插屏广告实例对象
*/
- (void)CXH_interstitialAdDidClose:(CXHAdSDKInterstitialAd *)interstitialAd{
    [self AdClose];
}

/**
 CXHAdSDKIntertitialAd展示回调
 
 @param interstitialAd 广告实例
 */
- (void)CXH_interstitialAdExposure:(CXHAdSDKInterstitialAd *)interstitialAd{
    [self AdShow];
}

/**
 CXHAdSDKIntertitialAd关闭落地页回调
 
 @param interstitialAd 广告实例
 */
- (void)CXH_interstitialAdCloseLandingPage:(CXHAdSDKInterstitialAd *)interstitialAd{
    
}


@end
